<template>
  <div class="search-list app-container">
    <div class="list-search-box mb10">
      <el-form :model="queryParams"
        ref="listForm"
        size="small"
        label-width="96px">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="地区名称"
              prop="name">
              <el-input v-model.trim="queryParams.name"
                placeholder="请输入地区名称"
                maxlength="30"
                style="width: 100%; max-width: 300px"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="3"
            style="margin-left: 20px">
            <el-button plain
              size="small"
              @click="resetForm('listForm')">重置</el-button>
            <el-button type="primary"
              size="small"
              @click="searchForm('listForm')">搜索</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="page_list-search">
      <div class="search-btn">
        <el-button type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd('1')">新增</el-button>
      </div>
    </div>
    <div class="custom-content_wrap custom-form-list_wrap">

      <div class="channel-management_table">
        <el-table ref="dataTable"
          v-loading="loading"
          :data="tableData"
          style="width: 100%; margin-bottom: 25px"
          row-key="uid"
          lazy
          :load="lazyLoad"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column :align="item.align ? item.align : 'center'"
            :prop="item.prop"
            :label="item.label"
            :min-width="item.minWidth"
            v-for="(item, index) in tableHeader"
            :key="index"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作"
            fixed="right"
            width="180">
            <template slot-scope="{ row }">
              <el-button type="text"
                size="mini"
                @click="handleAdd(row)"
                v-if="row.type != 'area'">新增</el-button>
              <el-button type="text"
                size="mini"
                @click="handleEdit(row)">编辑</el-button>
              <el-button type="text"
                size="mini"
                @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- <yd-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      /> -->
      <!-- <approve ref="approveRef" /> -->
    </div>

    <el-dialog class="custom-dialog_wrap"
      :title="optType == 2 ? '编辑地区' : '新增地区'"
      :visible.sync="areaOpen"
      width="500px"
      append-to-body
      @close="handleAreaBack">
      <el-form ref="areaForm"
        :model="areaForm"
        :rules="rules"
        label-width="120px">
        <el-form-item label="上级地区："
          prop="uid"
          v-if="pRow && optType == 1">
          <span>{{ pRow.name }}</span>
        </el-form-item>
        <el-form-item v-if="optType == 1"
          label="地区编号："
          prop="uid">
          <el-input v-model="areaForm.uid"
            style="width: 300px"
            maxlength="9"
            size="small"
            placeholder="请输入地区编号"
            @input="areaForm.uid = onInput(areaForm.uid, 0)"></el-input>
        </el-form-item>

        <el-form-item label="地区编号："
          prop="uid"
          v-if="optType == 2">
          <span>{{ pRow.uid }}</span>
        </el-form-item>

        <el-form-item label="地区名称："
          prop="name">
          <el-input v-model="areaForm.name"
            style="width: 300px"
            maxlength="9"
            size="small"
            placeholder="请输入地区名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
        class="dialog-footer">
        <el-button size="large"
          plain
          @click="handleAreaBack">取 消</el-button>
        <el-button size="large"
          type="primary"
          @click="handleAreaSubmit">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getReginList,
  addRegin,
  updateRegin,
  deteleRegin,
  getReginCityArea,
} from "@/api/base-dict/regionMgr";
import { onInput } from "@/utils/util";
export default {
  data () {
    return {
      loading: false,
      tableHeader: [
        {
          prop: "uid",
          label: "地区编号",
          minWidth: "200px",
        },
        { prop: "name", label: "地区名称", minWidth: "200px" },
      ],
      tableData: [],
      // total: 0,
      queryParams: {
        name: "",
      },
      areaOpen: false,
      areaForm: {
        uid: "",
        name: "",
      },
      rules: {
        uid: { required: true, message: "请输入地区编号", trigger: "blur" },
        name: {
          required: true,
          message: "请输入地区名称",
          trigger: "blur",
        },
      },
      pRow: null,
      optType: "1", //1新增， 2编辑
      lazyOBj: null,
    };
  },
  created () {
    this.getList();
  },
  methods: {
    onInput,
    lazyLoad (tree, treeNode, resolve) {
      // console.log(tree, treeNode, "-----------");
      getReginCityArea({
        type: tree.type,
        code: tree.uid,
      }).then((res) => {
        let { data } = res;
        data.forEach((item) => {
          if (item.type == "city") {
            item.hasChildren = true;
          }
        });
        resolve(data);
      });
    },
    relaodLazyLoad () {
      if (this.lazyOBj) {
        let val = this.lazyOBj.uid;
        let nodeMapVal = this.$refs.dataTable.store.states.lazyTreeNodeMap[val];
        if (nodeMapVal !== undefined && typeof nodeMapVal === "object") {
          if (nodeMapVal.length > 0) {
            getReginCityArea({
              type: this.lazyOBj.type,
              code: this.lazyOBj.uid,
            }).then((res) => {
              this.$refs.dataTable.store.states.lazyTreeNodeMap[val] = res.data;
              this.lazyOBj = null;
            });
          }
        }
      }
    },
    getList () {
      this.loading = true;
      // this.queryParams.contactPhone = this.queryParams.organName
      getReginList({
        name: this.queryParams.name,
      })
        .then((response) => {
          // this.tableData = response.rows;
          let data = response.data;
          data.forEach((item) => {
            if (item.type == "province" || item.type == "city") {
              item.hasChildren = true;
            }
          });
          this.tableData = this.handleTree(data, "uid", "puid");
          this.loading = false;

          // 需要懒加载替换的数据
          this.relaodLazyLoad();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    searchForm () {
      this.getList();
    },
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
    handleAdd (row) {
      this.optType = 1;
      if (row == "1") {
        //新增省
      } else {
        this.lazyOBj = row;
        this.pRow = row;
      }
      this.areaOpen = true;
    },
    handleEdit (row) {
      if (row.puid != 0) {
        this.lazyOBj = {
          type: row.ptype,
          uid: row.puid,
        };
      } else {
        this.lazyOBj = null;
      }
      this.areaForm = {
        uid: row.uid,
        name: row.name,
      };
      this.optType = 2;
      this.pRow = row;
      this.areaOpen = true;
    },
    handleDelete (row) {
      this.$confirm("确认删除地区", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (row.puid != 0) {
            this.lazyOBj = {
              type: row.ptype,
              uid: row.puid,
            };
          } else {
            this.lazyOBj = null;
          }
          deteleRegin({ uid: row.uid, type: row.type }).then((res) => {
            this.msgSuccess("删除成功");
            this.getList();
          });
        })
        .catch(() => { });
    },
    handleAreaBack () {
      this.areaForm = {
        uid: "",
        name: "",
      };
      if (this.$refs.areaForm) {
        this.$refs.areaForm.resetFields();
      }
      this.optType = 1;
      this.pRow = null;
      this.areaOpen = false;
    },
    handleAreaSubmit () {
      this.$refs.areaForm.validate((valid) => {
        if (valid) {
          if (this.optType == 2) {
            if (
              this.areaForm.uid != this.pRow.uid ||
              this.areaForm.name != this.pRow.name
            ) {
              updateRegin({
                ...this.areaForm,
                puid: this.pRow.puid,
                type: this.pRow.type,
                oldUid: this.pRow.uid,
              }).then((res) => {
                this.msgSuccess("保存成功");
                this.getList();
                this.handleAreaBack();
              });
            }
          } else {
            addRegin({
              ...this.areaForm,
              puid: this.pRow ? this.pRow.uid : "",
              type: !this.pRow
                ? "province"
                : this.pRow.type == "province"
                  ? "city"
                  : "area",
            }).then((res) => {
              this.msgSuccess("保存成功");
              this.getList();
              this.handleAreaBack();
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.list-search-box {
  background-color: #fff;
  padding: 15px 10px 0;
  border-radius: 6px;
}
.page_list-search {
  border-radius: 6px;
  width: 100%;
  background-color: #fff;
  padding: 10px;
  margin: 10px 0;
}
.custom-content_wrap {
  background-color: #fff;
  border-radius: 6px;
  padding: 10px;
}
</style>
